//
//  RequestManager.m
//  TalkBar
//
//  Created by xiaoling on 2018/3/5.
//  Copyright © 2018年 LSJ. All rights reserved.
//

#import "MantisRequestManager.h"


@interface MantisRequestManager()
@end


@implementation MantisRequestManager

+ (instancetype)shareManager{
    static MantisRequestManager * manager =  nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [MantisRequestManager new];
        manager.httpManager = [AFHTTPSessionManager manager];
        manager.httpManager.requestSerializer = [AFJSONRequestSerializer new];
        manager.httpManager.responseSerializer = [AFJSONResponseSerializer new];
        manager.httpManager.requestSerializer = [AFJSONRequestSerializer serializer]; // 请求
        manager.httpManager.responseSerializer = [AFJSONResponseSerializer serializer]; // 响应
        manager.httpManager.requestSerializer.timeoutInterval = 10.0f;
        // 设置请求头
        [manager.httpManager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [manager.httpManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"platForm"];
        
    });
    return manager;
}

//数据请求
+ (void)requestDataAPI:(NSString *)apiPath
                method:(HttpMethod)method
                params:(NSMutableDictionary *)params
             onSuccess:(NetworkSuccessBlock)successBlock
             onFailure:(NetworkFailureBlock)failureBlock{
    [self requestDataAPI:apiPath
                 baseUrl:@""
                  method:method
                  params:params
             headerField:nil
                progress:nil
               onSuccess:successBlock
               onFailure:failureBlock];
}

//自定义数据请求
+ (void)requestDataBaseUrl:(NSString *)baseUrl
                API:(NSString *)apiPath
                method:(HttpMethod)method
                params:(NSMutableDictionary *)params
             onSuccess:(NetworkSuccessBlock)successBlock
             onFailure:(NetworkFailureBlock)failureBlock{
    [self requestDataAPI:apiPath
                 baseUrl:baseUrl
                  method:method
                  params:params
             headerField:nil
                progress:nil
               onSuccess:successBlock
               onFailure:failureBlock];
}


+ (void)requestDataAPI:(NSString *)apiPath
               baseUrl:(NSString *)baseUrl
                method:(HttpMethod)method
                params:(NSMutableDictionary *)params
                headerField:(id)headerField
              progress:(void(^)(NSProgress *))progressBlock
             onSuccess:(NetworkSuccessBlock)successBlock
             onFailure:(NetworkFailureBlock)failureBlock{
    NSMutableDictionary * mutabParams = [[NSMutableDictionary alloc]initWithDictionary:params];
    
//    mutabParams[@"app_version"] = APP_VERSION;
//    mutabParams[@"app_type"] = @"iOS";
//    mutabParams[@"method"] = apiPath;
//    mutabParams[@"session"] = kUserToken;
    
    [self pureRequestWithUrl:baseUrl method:POST params:mutabParams headerField:headerField progress:progressBlock onSuccess:successBlock onFailure:failureBlock];
    
}

//最原始数据请求
+ (void)pureRequestWithUrl:(NSString *)baseUrl
                    method:(HttpMethod)method
                    params:(NSMutableDictionary*)mutabParams
               headerField:(id)headerField
                  progress:(void(^)(NSProgress *))progressBlock
                 onSuccess:(NetworkSuccessBlock)successBlock
                 onFailure:(NetworkFailureBlock)failureBlock{
    
    MantisRequestManager * manager = [MantisRequestManager shareManager];
        [headerField enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
            [manager.httpManager.requestSerializer setValue:object forHTTPHeaderField:key];
        }];
    
        static NSMutableDictionary *taskDic = nil;
        if(!taskDic)
            taskDic = [NSMutableDictionary dictionary];
    
        void (^theAFHTTPRequestOperationSuccess)(NSURLSessionDataTask *task, id responseObject) = ^void(NSURLSessionDataTask *task, id responseObject) {
            //请求的url拼接
            [self getCompareURL:task taskDic:taskDic];
            //解析responsepo
            NSError * error;
            id dict;
            
          if([responseObject isKindOfClass:[NSData class]]){
               dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
            }
            else {
                dict = responseObject;
            }
            successBlock(dict,task);
            [taskDic removeObjectForKey:task];
        };
    
        void (^theAFHTTPRequestOperationFailure)(NSURLSessionDataTask *task, NSError *error) = ^void(NSURLSessionDataTask *task, NSError *error) {
            //请求的url拼接
            [self getCompareURL:task taskDic:taskDic];
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)task.response;
    
            if ((long)httpResponse.statusCode >= 400 && (long)httpResponse.statusCode < 500){
                id errResp = task.response;
                NSLog(@"Error %ld: %@", (long)httpResponse.statusCode, error);
                if (errResp)
                {
                    successBlock(errResp,task);
                } else {
                    if (error.domain && [error.domain rangeOfString:@"com"].length > 0) {
                        NSError *err = [NSError errorWithDomain:@"网络连接错误" code:100000 userInfo:nil];
                        failureBlock(err,task);
                    } else {
                        failureBlock(error,task);
                    }
                }
            } else {
                NSLog(@"Error %ld: %@", (long)httpResponse.statusCode, error);
    
                NSError *err = [NSError errorWithDomain:@"请检查您的网络连接" code:100000 userInfo:nil];
                failureBlock(err,task);
            }
            [taskDic removeObjectForKey:task];
        };
    
        NSURLSessionDataTask *task = nil;
        switch (method) {
            case GET:{
                task = [manager.httpManager GET:baseUrl parameters:mutabParams headers:headerField progress:progressBlock success:theAFHTTPRequestOperationSuccess failure:theAFHTTPRequestOperationFailure];
    
                
                break;
            }
            case POST:{
              
                task = [manager.httpManager POST:baseUrl parameters:mutabParams headers:headerField progress:progressBlock success:theAFHTTPRequestOperationSuccess failure:theAFHTTPRequestOperationFailure];
                break;
            }
    
            default:
                break;
        }
        if (mutabParams.allKeys.count>0) {
            [taskDic setObject:mutabParams forKey:task];
        }
    
}




//封装一个方法获取当前正在请求的url
+(void)getCompareURL:(NSURLSessionDataTask*)task taskDic:(NSDictionary*)taskDic{
    
    //请求的url拼接
    NSString  *myUrlCompareStr = [NSString stringWithFormat:@"%@?",task.currentRequest.URL];
    NSDictionary *requestDic = [taskDic objectForKey:task];
    for (NSString *keyStr in requestDic.allKeys)
    {
        NSString *str1 = [NSString stringWithFormat:@"%@=%@&",keyStr,requestDic[keyStr]];
        myUrlCompareStr =  [myUrlCompareStr stringByAppendingString:str1];
    }
    myUrlCompareStr =  [myUrlCompareStr substringToIndex:myUrlCompareStr.length-1];
   // NSLog(@"第一种请求后台要的URL是：\n%@",myUrlCompareStr);
}






@end
